package com.copa.gameStore.exception;

import com.copa.gameStore.vo.ResponseVo;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import javax.validation.ValidationException;

/**
 * @author copa
 * @createDate 2022-09-22 18:16
 * @function
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    @ResponseBody
    @ExceptionHandler(AuthenticationException.class)
    public ResponseVo<String> authenticationExceptionHandler(AuthenticationException ex){
        return ResponseVo.errorMsg("认证异常：" + ex.getMessage());
    }

    @ResponseBody
    @ExceptionHandler(UsernameNotFoundException.class)
    public ResponseVo<String> usernameNotFoundExceptionHandler(UsernameNotFoundException ex){
        return ResponseVo.errorMsg("错误：" + ex.getMessage());
    }

    @ResponseBody
    @ExceptionHandler(InvalidGrantException.class)
    public ResponseVo<String> invalidGrantExceptionHandler(InvalidGrantException ex){
        return ResponseVo.errorMsg("错误：Bad credentials");
    }

    @ResponseBody
    @ExceptionHandler(BadCredentialsException.class)
    public ResponseVo<String> badCredentialsExceptionHandler(HttpServletResponse response, BadCredentialsException ex){
        return ResponseVo.errorMsg("错误：" + ex.getMessage());
    }

    @ResponseBody
    @ExceptionHandler(InvalidTokenException.class)
    public ResponseVo<String> invalidTokenExceptionHandler(HttpServletResponse response, InvalidTokenException ex){
        return ResponseVo.errorMsg("错误：" + ex.getMessage());
    }

    @ResponseBody
    @ExceptionHandler(RuntimeException.class)
    public ResponseVo<String> runtimeExceptionHandler(HttpServletResponse response, RuntimeException ex){
        return ResponseVo.errorMsg("系统繁忙，请稍后再试");
    }

    @ResponseBody
    @ExceptionHandler(ValidationException.class)
    public ResponseVo<String> validationExceptionHandler(HttpServletResponse response, RuntimeException ex){
        return ResponseVo.errorMsg(ex.getMessage());
    }


}
